package com.cloud.util.qrcode

import com.google.zxing.*
import com.google.zxing.client.j2se.BufferedImageLuminanceSource
import com.google.zxing.common.HybridBinarizer
import java.awt.image.BufferedImage
import java.io.File
import java.io.IOException
import java.lang.Boolean
import javax.imageio.ImageIO
import kotlin.Any
import kotlin.String


/**
 * 二维码生成和读的工具类
 *
 */
object QrCodeParseUtil {
    /**
     * 解析二维码,此方法解析一个路径的二维码图片
     * path:图片路径
     */
    fun deEncodeByPath(path: String?): String? {
        var content: String? = null
        var image: BufferedImage?
        try {
            image = ImageIO.read(File(path))
            val source: LuminanceSource = BufferedImageLuminanceSource(image)
            val binarizer: Binarizer = HybridBinarizer(source)
            val binaryBitmap = BinaryBitmap(binarizer)
            val hints: MutableMap<DecodeHintType, Any?> = HashMap()
            hints[DecodeHintType.CHARACTER_SET] = "UTF-8"
            val result = MultiFormatReader().decode(binaryBitmap, hints) //解码
//            println("图片中内容：  ")
//            System.out.println("content： " + result.text)
            content = result.text
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: NotFoundException) {
            //这里判断如果识别不了带LOGO的图片，重新添加上一个属性
            try {
                image = ImageIO.read(File(path))
                val source: LuminanceSource = BufferedImageLuminanceSource(image)
                val binarizer: Binarizer = HybridBinarizer(source)
                val binaryBitmap = BinaryBitmap(binarizer)
                val hints: MutableMap<DecodeHintType, Any?> = HashMap()
                //设置编码格式
                hints[DecodeHintType.CHARACTER_SET] = "UTF-8"
                //设置优化精度
                hints[DecodeHintType.TRY_HARDER] = Boolean.TRUE
                //设置复杂模式开启（我使用这种方式就可以识别微信的二维码了）
                hints[DecodeHintType.PURE_BARCODE] = Boolean.TYPE
                val result = MultiFormatReader().decode(binaryBitmap, hints) //解码
                println("图片中内容：  ")
                System.out.println("content： " + result.text)
                content = result.text
            } catch (e1: IOException) {
                e1.printStackTrace()
            } catch (e1: NotFoundException) {
                e1.printStackTrace()
            }
        }
        return content
    }

}